#include "GraphicsRotateOperation.h"
#include <GraphicsUtil.h>
#include <GraphicsBaseItem.h>
#include <QTransform>
#include <QDebug>

GraphicsRotateOperation::GraphicsRotateOperation(GraphicsBaseItemData& itemData, QObject* parent)
	:GraphicsBaseOperation(GraphicsOperationType::RotateOperation_Enum, itemData, parent)
{

}

GraphicsRotateOperation::~GraphicsRotateOperation()
{

}

void GraphicsRotateOperation::setRotateAngle(const QPointF& mouseScenePoint)
{
	if (m_itemData.getParentItem()) {
		m_itemData.getParentItem()->setAbsorptionLineVisable(GraphicsLineType::HorizontalEnum, false);
		m_itemData.getParentItem()->setAbsorptionLineVisable(GraphicsLineType::VerticalEnum, false);
	}

	// 鼠标所在点和图元中点组成的直线和图元的2个边平行
	const QPointF center = m_itemData.getScaleRect().center();
	QPointF mousePoint;
	if (m_itemData.getParentItem()) {
		mousePoint = m_itemData.getParentItem()->mapFromScene(mouseScenePoint);
	}
	else {
		mousePoint = mouseScenePoint;
	}
	const QLineF rotateLine(center, mousePoint);
	qreal rotateAngle = 90 - rotateLine.angle();
	rotateAngle = GraphicsUtil::normalizeAngle(rotateAngle);
	// 旋转吸附功能
	const int threshold = 5.0;
	if (std::abs(rotateAngle) < threshold || std::abs(rotateAngle - 360) < threshold) {
		rotateAngle = 0;
	}
	if (std::abs(rotateAngle - 90) < threshold) {
		rotateAngle = 90;
	}
	if (std::abs(rotateAngle - 180) < threshold) {
		rotateAngle = 180;
	}
	if (std::abs(rotateAngle - 270) < threshold) {
		rotateAngle = 270;
	}
	m_itemData.setRotateAngle(rotateAngle);
}

QTransform GraphicsRotateOperation::getRotateTransformOnCenter(qreal angle)
{
	QTransform transform;
	const QRectF rect = m_itemData.getScaleRect();
	const QSizeF size = rect.size();
	const QRectF boundingRect = GraphicsUtil::mapAnglePolygon(rect, angle).boundingRect();
	// 检查boundingRect是否在父图元中发生碰撞
	if (m_itemData.getParentItem() && !m_itemData.IsOriginOnCenter()) {
		const QRectF parentRect = m_itemData.getParentItem()->getItemData().getScaleRect();
		if (boundingRect.left() < 0)
			// 计算外接矩形与父图元左边界重合时候的旋转角度
			// TODO
			return transform;

		if (boundingRect.top() < 0)
			// 计算外接矩形与父图元上边界重合时候的旋转角度
			// TODO
			return transform;

		if (boundingRect.right() > parentRect.width())
			// 计算外接矩形与父图元右边界重合时候的旋转角度
			// TODO
			return transform;

		if (boundingRect.bottom() > parentRect.height())
			// 计算外接矩阵与父图元下边界重合时候的旋转角度
			return transform;

	}

	if (m_itemData.IsOriginOnCenter()) {
		transform.rotate(angle);
	}
	else {
		transform.translate(size.width() / 2, size.height() / 2);
		transform.rotate(angle);
		transform.translate(-size.width() / 2, -size.height() / 2);
	}
	return transform;
}
